var historyAlarm = {
    init: function () {
        this.initVehicleList();
        this.initAlarmTypeList();
        this.bindquery();
        this.tempAlarmType = alarmType;
        this.queryDetail('.queryAlarm', '#senior', 41, function (height) {
            var flexIgridH = nav.whiceH[1] - 112 - height + 30 + 'px';
            $('#queryResult').flexResize('auto', flexIgridH);
        });
        /** 初始化日期 * */
        var date = new Date();
        $("#inputStartDate").val(global.getToday(date));
        $("#inputEndDate").val(global.getTime(date));
        this.historyAlarm();
        this.handleAlarmSave();
    },

    initVehicleList: function () {
        $.ajax({
            type: 'post',
            url: appCtx + "/system/vehicle/loadUserVehicle.html",
            cache: false,
            dataType: "JSON",
            success: function (data) {
                if (data) {
                    var selectStr = "";

                    selectStr += "<option value=''>请选择车牌号码</option>";
                    var newSelectStr = "";

                    newSelectStr += "<option value=''>请选择车牌号码</option>";

                    $.each(data.vehicleList, function (entryIndex, entry) {
                        selectStr += "<option value='" + entry.vehicleId + "'>"
                            + entry.registrationNO + "</option>";
                        newSelectStr += "<option value='" + entry.commNo + "'>"
                            + entry.registrationNO + "</option>";
                    });
                    // 当日报警车牌号
                    $('#quaryCar').html(selectStr);
                    // 待处理报警
                    $('#pendingQuaryCar').html(newSelectStr);
                }
            }
        });
    },
    initAlarmTypeList: function () {
        $.ajax({
            type: 'post',
            url: appCtx + "alarm/queryAlarm.html?time="
            + new Date().getTime(),
            cache: false,
            dataType: "JSON",
            success: function (data) {
                if (data) {
                    var selectStr = "";
                    selectStr += "<option value=''>请选择报警类型</option>";
                    $.each(
                        data.vehicleList,
                        function (entryIndex, entry) {
                            // 只显示符合业务的报警数据
                            if (entry.AlarmKindID == 2 || entry.AlarmKindID == 3 || entry.AlarmKindID == 1 || entry.AlarmKindID == 316
                                || entry.AlarmKindID == 321 || entry.AlarmKindID == 100501 || entry.AlarmKindID == 100504
                                || entry.AlarmKindID == 100503 || entry.AlarmKindID == 100504) {
                                selectStr += "<option value='"
                                    + entry.AlarmKindID
                                    + "'>"
                                    + entry.alarmName
                                    + "</option>";
                            }
                        });
                    $('#quaryType').html(selectStr);
                }
            }
        });
    },
    /**
     * 导出历史信息
     */
    exportSimCard: function () {

        var options = $("#queryResult").getOptions();
        var total = options.total;
        if (total == 0) {
            global.ajaxLoading.pop("无导出数据", false, 2000);
            return;
        }
        var pages = options.pages;
        //设置默认的开始结束页
        $("#StartPageIndex").val(1);
        $("#EndPageIndex").val(pages);
        //显示导出窗口
        $("#exportModal").modal('show');
    },
    getColumn: function () {
        var getAlarmName = function (msg) {
            if (msg != "") {
                var AlarmName = historyAlarm.tempAlarmType.getAlarmName(Number(msg));
                return AlarmName;
            }
        };
        function formatSimCard(data) {
            var time = "";
            if (data != "") {
                console.log(data + "-" + typeof(data));
                time = global.getTime(new Date(JSON.parse(data)));
            }

            var str = '<span>' + time + '</span>';
            return str;
        };
        return [
            {
                display: '车牌号',
                name: 'registrationNO',
                width: 100,
                sortable: false,
                align: 'left',
                checked: 'checked'
            },
            {
                display: '自编号',
                name: 'internalNo',
                width: 80,
                sortable: false,
                align: 'left',
            },
            {
                display: '车队',
                name: 'vehicleTeamName',
                width: 150,
                sortable: false,
                align: 'left',
            },
            {
                display: '报警类型',
                name: 'alarmkind',
                width: 80,
                sortable: false,
                align: 'left',
                paramcolnames: ['alarmkind'],
                handlefunction: getAlarmName,
            },
            {
                display: '报警来源',
                name: 'alarmSource',
                width: 60,
                sortable: false,
                align: 'left',
            },
            {
                display: '报警说明',
                name: 'alarmParam',
                width: 220,
                sortable: false,
                align: 'left',
                // paramcolnames:['alarmParam'],
                // handlefunction:formatAlarmInfo,
                showTitle: "alarmParam"
            },
            {
                display: '报警时间',
                name: 'alarmTime',
                width: 130,
                sortable: false,
                align: 'left',
            },
            {
                display: '处理时间',
                name: 'dealTime',
                width: 150,
                sortable: false,
                align: 'left',
            },
            {
                display: '处理内容',
                name: 'dealContent',
                width: 150,
                sortable: false,
                align: 'left',
                // paramcolnames:['dealContent'],
                // handlefunction:formatAlarmInfo,
                showTitle: 'dealContent'
            },
            {
                display: '处理人',
                name: 'dealer',
                width: 70,
                sortable: false,
                align: 'left',
            }
        ]
    },
    exportComfirm: function () {
        var me = this;
        var options = $("#queryResult").getOptions();
        //总记录数
        var total = options.total;
        //开始页数
        var StartPage = $("#StartPageIndex").val();
        //结束页数
        var EndPage = $("#EndPageIndex").val();
        var validate = true;
        var msg = "";
        if (!StartPage || StartPage == 0) {
            msg += "【起始页不能为空或者0】";
            validate = false;
        }
        if (!EndPage || EndPage == 0) {
            msg += "【结束页不能为空或者0】";
            validate = false;
        }

        if (StartPage && EndPage && EndPage < StartPage) {
            msg += "【结束页要大于起始页】";
            validate = false;
        }
        if (!validate) {
            global.ajaxLoading.pop(msg, false, 2000);
            return;
        }
        $('#exportModal').modal('hide');
        global.ajaxLoading.pop("正在导出,请稍后.....", true, 2000);
        //每页大小
        var pagesize = options.rp;

        //获取导出的参数
        var exportParams = options.exportParams;
        if ((EndPage - StartPage + 1) * pagesize > 60000 && total > 60000) {
        	global.ajaxLoading.pop("最多只能导出60000条数据", true, 2000);
            return
        }
        var header1 = JSON.stringify(historyAlarm.getColumn());
        var colModelList = new Array();//表头
        colModelList.push(header1);
        var colModel = $.toJSON(colModelList);
        var paramsGrid = {
            queryParams:JSON.stringify(historyAlarm.getparams()),
            colModel: colModel,
            title: "历史报警数据",
            imgsrc: null,
            StartPage: StartPage,
            EndPage: EndPage,
            pagesize: pagesize
        };
        post(appCtx + "alarm/exportHistory.html", paramsGrid);
    },
    bindquery: function () {
        $("a[name='exportSimCardBtn']").bind('click', function () {
            historyAlarm.exportSimCard();
        });
        $("#confirmExport").click(function () {
            historyAlarm.exportComfirm();
        })
        var _this = this;
        $('#queryAlarm').click(function () {
            // 历史报警查询不能超过三天
            var start = $("#inputStartDate").val().replace(/-/g, "/");
            var end = $("#inputEndDate").val().replace(/-/g, "/");
            if ((new Date(end).getTime() - new Date(start).getTime())
                / (1000 * 60 * 60 * 24) > 3) {
                global.ajaxLoading.pop("历史报警查询不能超过三天", false, 1000);
                return;
            }
            $("#queryResult").flexOptions({
                newp: 1,
                params: historyAlarm.getparams()
            }).flexReload();
        });
        $('#dealAlarm').click(function () {
            $('#handerHistoryContent').val("");
            var vehicle = [];
            var alarmType = [];
            var alarmTime = [];
            var alarmName = [];
            $('#queryResult')
                .find('.trSelected')
                .each(
                    function () {
                        var tdArr = $(this).children();
                        if (tdArr.eq(10).find('div')
                                .html() == null
                            || tdArr.eq(10).find(
                                'div').html() == ''
                            || tdArr.eq(10).find(
                                'div').html() == '&nbsp;') {
                            vehicle
                                .push(tdArr
                                    .eq(2)
                                    .find('div')
                                    .html());
                            alarmType
                                .push(tdArr
                                    .eq(3)
                                    .find('div')
                                    .html());
                            alarmTime
                                .push(tdArr
                                    .eq(9)
                                    .find('div')
                                    .html());
                            alarmName
                                .push(tdArr
                                    .eq(6)
                                    .find('div')
                                    .html());
                        }
                    });

            var vehicles = vehicle[0];
            var alarmTypes = alarmType[0];
            for (var i = 0; i < vehicle.length; i++) {
                if (vehicle[i] != vehicles) {
                    global.ajaxLoading
                        .pop("车辆不一致", false, 1000);
                    return;
                }
                if (alarmType[i] != alarmTypes) {
                    global.ajaxLoading.pop("报警类型不一致", false,
                        1000);
                    return;
                }
            }
            if (vehicle == null || vehicle == "") {
                if ($('#queryResult').find('.trSelected')
                        .size() > 0) {
                    global.ajaxLoading.pop("你选择的报警数据已经处理",
                        false, 1000);
                    return;
                } else {
                    global.ajaxLoading
                        .pop("请选择车辆", false, 1000);
                    return;
                }
            }
            $('#handlerhisAlarmTime').val(alarmTime);
            $("#handlerhisVevhicleid").val(vehicles);
            $("#handlerhisAlarmType").val(alarmTypes);
            $("#showHistoryAlarmType").val(alarmName[0]);
            historyAlarm.queryHistoryAlarm();
        });
    },
    queryHistoryAlarm: function () {
        $("#handlerHistoryTime").val(global.getTime(new Date()));
        $('#handlehistoryAlarm').modal('show');
    },
//	/**
//	 * 日历的显示
//	 */
    queryDetail: function (showDome, clickDome, height, callback) {
        $(clickDome).on('click', function () {
            if ($(this).hasClass('active')) {
                $(this).removeClass('active');
                $(showDome).css('height', height);
            } else {
                $(this).addClass('active')
                $(showDome).css('height', 'auto');
            }
            var h = $('#historyAlarm').height();
            callback && callback(h);
        })
    },
    /**
     * 重新加载历史报警
     */
    reloadHistoryAlarm: function () {
        var page = $("#queryResult").page;

        $("#queryResult").flexOptions({
            newp: page,
            params: historyAlarm.getparams()
        }).flexReload();

    },
    /**
     * 历史报警
     */
    historyAlarm: function () {
        var quaryCar = function () {
            $("#quaryCar").select2();
            $("#quaryType").select2();
            $("#quaryCondition").select2();
            $("#ishandle").select2();
        };
        quaryCar();
        var formatAlarmAction = function (vehicleID, alarmkind, alarmType,
                                          alarmTime, checked, lon, lat, head, gpsSpeed) {
            if (checked != 'false') {
                str = "<a class='viewHisMap' vehilceID=\""
                    + vehicleID
                    + "\" alarmType=\""
                    + historyAlarm.tempAlarmType.getAlarmName(alarmkind)
                    + "\" alarmkind=\""
                    + alarmkind
                    + "\" lon=\""
                    + lon
                    + "\" lat=\""
                    + lat
                    + "\" head=\""
                    + head
                    + "\" gpsSpeed=\""
                    + gpsSpeed
                    + "\" alarmTime=\""
                    + alarmTime
                    + "\" href='javascript:void(0)' style='float: left;'><font color='blue'>查看地图</font></a>";
                return str;
            } else {
                var str = "<a class='alarmHistoryDeal' vid=\""
                    + vehicleID
                    + "\" alarmType=\""
                    + historyAlarm.tempAlarmType.getAlarmName(alarmkind)
                    + "\" alarmkind=\""
                    + alarmkind
                    + "\"alarmTime=\""
                    + alarmTime
                    + "\" href='javascript:void()'style='float: left;' ><font color='blue'>处理报警</font></a>  ";
                str +="<span class ='db fl' style='width:10px;height:12px;text-align:center;'>|</span>";
                str += "<a class='viewHisMap' vehilceID=\""
                    + vehicleID
                    + "\" alarmType=\""
                    + historyAlarm.tempAlarmType.getAlarmName(alarmkind)
                    + "\" alarmkind=\""
                    + alarmkind
                    + "\" lon=\""
                    + lon
                    + "\" lat=\""
                    + lat
                    + "\" head=\""
                    + head
                    + "\" gpsSpeed=\""
                    + gpsSpeed
                    + "\" alarmTime=\""
                    + alarmTime
                    + "\" href='javascript:void(0)' style='float: left;'><font color='blue'>查看地图</font></a>";
                return str;
            }
        };
        $('body').on(
            'click',
            '.alarmHistoryDeal',
            function () {
                $('#handerHistoryContent').val("");
                var vid = $(this).attr("vid");
                var alarmType = $(this).attr("alarmkind");
                var alarmTime = $(this).attr("alarmTime");
                var params = {
                    "VehicleID": vid,
                    "AlarmType": alarmType,
                    "alarmTime": alarmTime
                };
                $('#handlerhisAlarmTime').val(alarmTime), $(
                    "#handlerhisVevhicleid").val(vid), $(
                    "#handlerhisAlarmType").val(alarmType), $(
                    "#showHistoryAlarmType").val(
                    historyAlarm.tempAlarmType.getAlarmName($(this).attr("alarmkind")));
                historyAlarm.queryHistoryAlarm();

            });
        $('body').on(
            'click',
            '.viewHisMap',
            function () {
                var vehilceID = $(this).attr("vehilceID");
                var alarmType = $(this).attr("alarmType");
                var alarmkind = $(this).attr("alarmkind");
                var alarmTime = $(this).attr("alarmTime");
                var lon = $(this).attr("lon");
                var lat = $(this).attr("lat");
                var head = $(this).attr("head");
                var gpsSpeed = $(this).attr("gpsSpeed");
                window.open(appCtx
                    + 'alarm/history/location.html?vehicleID='
                    + vehilceID + "&alarmType=" + alarmType
                    + "&alarmTime=" + alarmTime + "&lon=" + lon
                    + "&lat=" + lat + "&head=" + head + "&gpsSpeed="
                    + gpsSpeed);
            });

        var queryResult = function () {
            var formatAlarmInfo = function (msg) {
                var str = '<div class="textOverFlow" style="padding-left:0;padding-right:0;" title="'
                    + msg + '">' + msg + '</div>';
                return str;
            };
            var getAlarmName = function (msg) {
                if (msg != "") {
                    var AlarmName = historyAlarm.tempAlarmType.getAlarmName(Number(msg));
                    return AlarmName;
                }
            };
            $("#queryResult").flexigrid(
                {
                    dataType: 'json',
                    url: appCtx + 'alarm/history/list.html?time='
                    + new Date().getTime(),
                    params: historyAlarm.getparams(),
                    contentType: "application/json; charset=utf-8",
                    method: 'POST',
                    colModel: [
                        {
                            display: '车牌号',
                            name: 'registrationNO',
                            width: 100,
                            sortable: false,
                            align: 'left',
                            checked: 'checked'
                        },
                        {
                            name: 'vehicleID',
                            width: 80,
                            sortable: false,
                            hide: true,
                            align: 'left',
                        },
                        {
                            name: 'alarmkind',
                            width: 80,
                            sortable: false,
                            hide: true,
                            align: 'left',
                        },
                        {
                            display: '自编号',
                            name: 'internalNo',
                            width: 80,
                            sortable: false,
                            align: 'left',
                        },
                        {
                            display: '车队',
                            name: 'vehicleTeamName',
                            width: 150,
                            sortable: false,
                            align: 'left',
                        },
                        {
                            display: '报警类型',
                            name: 'alarmkind',
                            width: 80,
                            sortable: false,
                            align: 'left',
                            paramcolnames: ['alarmkind'],
                            handlefunction: getAlarmName,
                        },
                        {
                            display: '报警来源',
                            name: 'alarmSource',
                            width: 60,
                            sortable: false,
                            align: 'left',
                        },
                        {
                            display: '报警说明',
                            name: 'alarmParam',
                            width: 220,
                            sortable: false,
                            align: 'left',
                            // paramcolnames:['alarmParam'],
                            // handlefunction:formatAlarmInfo,
                            showTitle: "alarmParam"
                        },
                        {
                            display: '报警时间',
                            name: 'alarmTime',
                            width: 130,
                            sortable: false,
                            align: 'left',
                        },
                        {
                            display: '处理时间',
                            name: 'dealTime',
                            width: 150,
                            sortable: false,
                            align: 'left',
                        },
                        {
                            display: '处理内容',
                            name: 'dealContent',
                            width: 150,
                            sortable: false,
                            align: 'left',
                            // paramcolnames:['dealContent'],
                            // handlefunction:formatAlarmInfo,
                            showTitle: 'dealContent'
                        },
                        {
                            display: '处理人',
                            name: 'dealer',
                            width: 70,
                            sortable: false,
                            align: 'left',
                        },
                        {
                            display: '操作',
                            name: 'Handle',
                            paramcolnames: ["vehicleID", "alarmkind",
                                "alarmType", "alarmTime",
                                "checked", "longitude", "latitude",
                                "head", "gpsSpeed"],
                            handlefunction: formatAlarmAction,
                            width: 150,
                            sortable: false,
                            align: 'left',
                        }],

                    resizable: false,
                    sortname: "terminalId",// 第一次加载数据时排序列
                    sortorder: "desc",// 第一次加载数据时排序类型
                    usepager: true,// 是否分页，默认为true。
                    showToggleBtn: false,
                    showTableToggleBtn: false,// 是否显示收起/打开按钮,默认不显示。
                    useRp: true,// 是否可以动态设置每页显示的结果数，默认为false。
                    rp: 10,// 每页记录数，默认为10
                    rpOptions: [10, 50, 100, 300, 500], // 每页结果数
                    checkbox: true,// 是否要多选框,默认为false。
                    rowId: 'terminalId',// 多选框绑定行的id,只有checkbox :
                    // true时才有效。
                    singleSelect: true,
                    width: 'auto',// 表格宽度
                    height: nav.whiceH[1] - 123, // 表格高度
                    titDisplay: false,
                    onSuccess: function (data) {

                    },
                    onSelectRow: function (row) {

                    },
                    onSelectAllRow: function (data) {

                    }
                });
        };
        queryResult();
    },
    getparams: function () {
        var vid = $("#quaryCar").val();
        var alarmType = $("#quaryType").val();
        var alarmCondition = $("#quaryCondition").val();
        var handle = $("#ishandle").val();
        var dealer = $("#dealPeople").val();
        var startDate = $("#inputStartDate").val();
        var endDate = $("#inputEndDate").val();
        var params = [{
            name: 'vid',
            value: vid
        }, {
            name: 'alarmType',
            value: alarmType
        }, {
            name: 'alarmCondition',
            value: alarmCondition
        }, {
            name: 'handle',
            value: handle
        }, {
            name: 'dealPeople',
            value: dealer
        }, {
            name: 'startDate',
            value: startDate
        }, {
            name: 'endDate',
            value: endDate
        }];
        return params;
    },


    HistoryAlarmHandler: function () {
        if ($("#handlerhisVevhicleid").val() == "") {
            global.ajaxLoading.pop("未选择处警车辆,不能处警", false, 1000);
            return;
        }
        if ($("#handlerhisAlarmType").val() == "") {
            global.ajaxLoading.pop("未选择处警类型,不能处警", false, 1000);
            return;
        }
        if ($("#handlerhisAlarmTime").val() == "") {
            global.ajaxLoading.pop("未选择报警时间,不能处警", false, 1000);
            return;
        }

        var params = {
            "vehicleId": $("#handlerhisVevhicleid").val(),
            "alarmType": $("#handlerhisAlarmType").val(),
            "alarmTime": $("#handlerhisAlarmTime").val(),
            "result": $("#modal-hisoryform-select").val(),
            "content": $("#handerHistoryContent").val(),
        };

        $.ajax({
            url: appCtx + 'alarm/history/handler.html?time='
            + new Date().getTime(),
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            cache: 'false',
            data: JSON.stringify(params),
            success: function (result) {
                if (result.data == 0) {
                    global.ajaxLoading.close();
                    $('#handlehistoryAlarm').modal('hide');
                    historyAlarm.reloadHistoryAlarm();
                } else {
                    global.ajaxLoading.pop(result.msg, true, 1000);
                    global.ajaxLoading.close();
                }
            }
        });

    },
    /**
     * 处理报警保存
     */
    handleAlarmSave: function () {
        $('#handleAlarmSave').click(function () {
            if ($.trim($("#handerContent").val()) == '') {
                global.ajaxLoading.pop('请输入处警内容', false, 800);
                return;
            }
            global.ajaxLoading.pop('正在处警,请稍等....', true);
            historyAlarm.realTimeAlarmHandler();
        });
        $('#handleHistoryAlarmSave').click(function () {
            if ($.trim($("#handerHistoryContent").val()) == '') {
                global.ajaxLoading.pop('请输入处警内容', false, 800);
                return;
            }
            historyAlarm.HistoryAlarmHandler();
            global.ajaxLoading.pop('正在保存', true, 1000);
        });
    },
};


historyAlarm.init();
